//
//  QZViewController.m
//  map
//
//  Created by 000 on 16/10/19.
//  Copyright © 2016年 faner. All rights reserved.
//

#import "QZViewController.h"

//因保存引入
//#import <BmobSDK/BmobObject.h>
#import "BmobSDK/Bmob.h"
//#import <BmobSDK/BmobFile.h>
#import "QZGoodsVC.h"

//以下为设置大头针及气泡内容引入
#import "QZAnnotation.h"
#import "QZAnnotationView.h"

//#import "QZDeskLineVC.m"
#import "LiChengVC.h"

#import "QZGeRenVC.h"
//#import "Utility.h"
#import "constant.h"
@interface QZViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>
{
    NSMutableArray *allDeskArray;
    NSMutableArray *allCLArray;
    NSMutableArray *startDeskmArray;
    NSMutableArray *startCLArray;
    NSMutableArray *startMarkerArray;
    
    NSMutableArray *secondDeskArray;//第二层任务所在数组
    NSMutableArray *secondCLArray; //第二层坐标所在数组
    NSMutableArray *secondPicArray;//第二层图片所在数组
    NSMutableArray *secondGoodsPicA;//第二层任务物品所在数组
    
    NSMutableArray *thirdCountArray;//第三层个数所在数组
    NSMutableArray *thirdDeskArray;//第三层任务所在数组
    NSMutableArray *thirdCLArray;//第三层坐标所在数组
    NSMutableArray *thirdPicArray;//第三层图片所在数组
    NSMutableArray *thirdGoodsPicA;//第三层任务物品所在数组
    
    NSMutableArray *fourthLinkArray;//第四层连线数组
    
    NSMutableArray *lineNameArray;//任务组的名称
    
    NSMutableArray *countArray;//每组任务数量的数组
    NSMutableArray *linklineArray;
    
    MKPolyline *selflinkNext;//当前到下一任务间的连线
    MKPolyline *commonPolyline11;
    MKPolyline *grayLine;
    
    MKCircle *circle;
    CLLocationCoordinate2D touchMapCoordinate;
    
    NSMutableArray *removeOBJArray;//取消时删除的数组
    
    int cacheCount;
    int startI;
//    BOOL isHaveValue;//是否已有值
    
    
    BOOL isLoadFirst;//是否第一次加载时
    BOOL isActivate;//是否激活
    int judgeCount;//判断有几个达到条件
    int getCount;//得到计数
    
//    BOOL isThirdSuc;//是否加载第三层成功
    
    
    
    NSUserDefaults *userDefaults1;
    BOOL isSaveLicheng;
    
    /*作第二次登陆处理*/
//    int hadCount;
//    int hadDesk;
    
    BOOL isCloseMargin;//是否关闭计算
    
    //删除操作
    NSMutableArray *removeArray;//需移除的数组
}
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;//定位坐标
@property (nonatomic, strong) CLGeocoder *geocoder;//地理编码用
@property (nonatomic, assign) CLLocationCoordinate2D currentCoordinate,deskCoordinate;//获取当前定位坐标（修改后的）
/**取消按钮*/
@property (weak, nonatomic) IBOutlet UIButton *cancleDeskB;

@property (weak, nonatomic) IBOutlet UIButton *backHomeB;
@property (weak, nonatomic) IBOutlet UIButton *signInB;
@property (weak, nonatomic) IBOutlet UIButton *activeBtn;
- (IBAction)activeBC:(id)sender;
- (IBAction)lichengBC:(id)sender;
- (IBAction)wupinBC:(id)sender;
- (IBAction)gerenBC:(id)sender;
- (IBAction)signInBC:(id)sender;
- (IBAction)backHomeBC:(id)sender;
//取消按钮被电击
- (IBAction)cancleDeskBC:(id)sender;

@end

@implementation QZViewController

#pragma mark - 懒加载
- (CLLocationManager *)locationManager
{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        //设置代理
        _locationManager.delegate = self;
        //每隔多远定位一次
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        
        [_locationManager startUpdatingLocation];
        //精确度
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        
#if 1
        //-----iOS8.0+需要添加下面的方法才能定位-----//
        
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            //前后台定位授权（必须在Info.plist文件中添加NSLocationAlwaysUsageDescription字段设置显示的授权提示描述 否则无法定位）
            [_locationManager requestAlwaysAuthorization];
            
            //前台定位授权（必须在Info.plist文件中添加NSLocationWhenInUseUsageDescription字段设置显示的授权提示描述 否则无法定位）
            [_locationManager requestWhenInUseAuthorization];
        }
#endif
    }
    return _locationManager;
}
- (CLGeocoder *)geocoder
{
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        //如果响应执行下么的方法
        [self.locationManager requestAlwaysAuthorization];
    }
    self.navigationItem.title = @"首页";
    self.navigationItem.hidesBackButton = YES;//隐藏返回按钮
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    cacheCount= 0 ;
    userDefaults1 = [NSUserDefaults standardUserDefaults];
    startI = 100;
    
    isActivate = NO;//是否激活    
     [self location];
    
    isLoadFirst=YES;//第一次进入
    isCloseMargin=NO;
    /*作第二次登陆处理*/
    [self loadThirdCount];
    [self loadSecondData];
    getCount = 0;//在计算方法中得到的计数
}

#pragma mark - MKMapViewDelegate 制作大头针
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //如果是当前位置就设置为nil
    if (annotation == mapView.userLocation) {
        return nil;
    }else{
        QZAnnotation *myAnnotation = [[QZAnnotation alloc] init];
        myAnnotation = annotation;
        QZAnnotationView *myAnnotationView = [QZAnnotationView getQZAnnotationViewWithMapView:mapView andAnnotation:annotation];
        
        myAnnotationView.image = [UIImage imageNamed:@"desk"];
        [myAnnotationView.leftButton setBackgroundImage:myAnnotation.image forState:UIControlStateNormal];
        return myAnnotationView;
    }
    
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    if (view.annotation == mapView.userLocation) {
        return ;
    }else{
        QZAnnotation *annotation = (QZAnnotation *)view.annotation;
        
        CLLocation *current1=[[CLLocation alloc] initWithLatitude:self.currentCoordinate.latitude longitude:self.currentCoordinate.longitude];
        CLLocation *loct = [[CLLocation alloc] initWithLatitude:annotation.coordinate.longitude longitude:annotation.coordinate.longitude];
        CLLocationDistance distantMarker = [current1 distanceFromLocation:loct];
        
        if (judgeCount>1 &&distantMarker <kMargin) {
            isCloseMargin = YES;
            cacheCount = [annotation.marker intValue];
            [self setActiveBtnStateHighlight];
        }
    }

}
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    isCloseMargin = NO;
    [self setActiveBtnStateNormal];
    self.activeBtn.hidden = YES;
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    self.currentCoordinate = userLocation.coordinate;
}

#pragma mark - CLLocationManagerDelegate
#pragma mark 自己位置的代理方法
//-----------------------时时定位－－－－－－－－－－－－－－－－－－－－－－－－－－－－
//CLLocationManager委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //得到newLocation
    CLLocation *loc = [locations objectAtIndex:0];
    
    [self.mapView removeOverlay:circle];
    [self addCover];
    if (isCloseMargin==YES) {
    }else{
        if (isActivate == NO) {
            self.cancleDeskB.hidden = YES;
            [self countMargin1];
        }else{
            self.cancleDeskB.hidden = NO;
            [self countMargin];
        }
    }
}
#pragma mark 计算第三层任务距离自己的位置
- (void)countMargin
{
    //当前坐标
    CLLocation *current=[[CLLocation alloc] initWithLatitude:self.currentCoordinate.latitude longitude:self.currentCoordinate.longitude];
    CLLocationDistance distantMargin;
    if (thirdCLArray.count>0&&startI-100<thirdCLArray.count) {
        
        distantMargin = [current distanceFromLocation:thirdCLArray[startI-100]];
        
    } else {
        distantMargin = 10000000;
    }
    
    if (distantMargin <kMargin &&distantMargin>0) {
        [self setSignBtnStateHighlight];
    } else {
        [self setSignBtnStateNormal];
        self.signInB.hidden = NO;
    }
    
}

#pragma mark 跟踪自己的位置
- (void)location//定位方法
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.026416, 0.019511);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.currentCoordinate, span);
    [self.mapView setRegion:region animated:YES];
    //显示用户的位置
    self.mapView.showsUserLocation = YES;
    // 是否显示指南针
    self.mapView.showsCompass = YES;
    // 是否显示比例尺
    self.mapView.showsScale = YES;
    // 是否显示交通
    self.mapView.showsTraffic = YES;
    // 是否显示建筑物
    //    self.mapView.showsBuildings = NO;
    //    self.mapView.mapType = MKMapTypeStandard;
    //追踪用户的位置
    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}
#pragma mark 计算第一层任务距离自己的位置
- (void)countMargin1
{
    //当前坐标
    CLLocation *current=[[CLLocation alloc] initWithLatitude:self.currentCoordinate.latitude longitude:self.currentCoordinate.longitude];
    if (startCLArray.count == 0) {
        [self setActiveBtnStateNormal];
    }else{
        CLLocationDistance distant1;
        //判断有几个达到条件
        judgeCount = 0;
        for (int i = 0; i<startCLArray.count; i++) {
            distant1 = [current distanceFromLocation:startCLArray[i]];
            if (distant1<=kMargin) {
                judgeCount++;
                getCount = [startMarkerArray[i] intValue];
            } else {
            }
        }//for在此结束
        if (judgeCount>1) {
            [self setActiveBtnStateNormal];
            self.activeBtn.hidden =YES;
        } else if (judgeCount ==1){
            [self setActiveBtnStateHighlight];
            cacheCount = getCount;
        } else {
            [self setActiveBtnStateNormal];
        }
    }
}
#pragma mark 给定位添加图层
-(void)addCover
{
    circle = [MKCircle circleWithCenterCoordinate:self.currentCoordinate radius:kMargin];
    [self.mapView addOverlay:circle];
}
#pragma mark - MKMapViewDelegate
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if (overlay == grayLine) {
        
        MKPolygonView *grayLineView = [[MKPolylineView alloc] initWithPolyline:grayLine];
        grayLineView.fillColor = [UIColor grayColor];
        grayLineView.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.6 alpha:0.3];
        grayLineView.lineWidth = 10;
        
        return grayLineView;
        
    }else if(overlay == commonPolyline11) {
        MKPolygonView * routeLineView= [[MKPolylineView alloc] initWithPolyline:commonPolyline11];
        routeLineView.fillColor = [UIColor redColor];
        routeLineView.strokeColor = [UIColor redColor];
        routeLineView.lineWidth = 10;
        
        return routeLineView;
    } else if (overlay == circle)
    {
        MKCircleView *circleView = [[MKCircleView alloc] initWithCircle:circle];
        
        circleView.lineWidth = 5.f;
        circleView.strokeColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:0.8];
        circleView.fillColor = [UIColor colorWithRed:1.0 green:0.8 blue:0.0 alpha:0.2];
        circleView.lineDashPhase = 10;
        return circleView;
    }
    return nil;
}

/** 设置activeBtn按钮的属性 灰色 */
- (void)setActiveBtnStateNormal
{
    self.activeBtn.hidden = YES;
    [self.activeBtn setBackgroundImage:[UIImage imageNamed:@"active_normal"] forState:UIControlStateNormal];
    self.activeBtn.userInteractionEnabled = NO;
}
/** 设置activeBtn按钮的属性 */
- (void)setActiveBtnStateHighlight
{
    self.activeBtn.hidden = NO;
    [self.activeBtn setBackgroundImage:[UIImage imageNamed:@"active_highlight"] forState:UIControlStateNormal];
    self.activeBtn.userInteractionEnabled = YES;
    
}
/** 设置activeBtn按钮的属性 灰色 */
- (void)setSignBtnStateNormal
{
    self.signInB.hidden = YES;
    [self.signInB setBackgroundImage:[UIImage imageNamed:@"graysign"] forState:UIControlStateNormal];
    self.signInB.userInteractionEnabled = NO;
}
/** 设置activeBtn按钮的属性 */
- (void)setSignBtnStateHighlight
{
    self.signInB.hidden = NO;
    [self.signInB setBackgroundImage:[UIImage imageNamed:@"sign"] forState:UIControlStateNormal];
    self.signInB.userInteractionEnabled = YES;
}

#pragma mark - xib中的方法
- (IBAction)activeBC:(UIButton*)sender
{/** 任务已经激活 **/
    isActivate = YES;
    /**  进入任务 */
    [self enterDesk];
    startI++;
    [self updataThirdCound];
    [self savePersonSignData];
}
//进入当前任务线
- (void)enterDesk
{
    startI = 100;
    [self setSignBtnStateNormal];
    [self loadThirdData];
}
//更新数据progress 哪一条任务线
- (void)updataActiveSave
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"progress"];
    [bquery orderByAscending:@"createdAt"];
    [bquery whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    [bquery calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        NSString *thiredId;
        NSString *thirdCount = [NSString stringWithFormat:@"%d",cacheCount];
        for (BmobObject *obj in array) {
            thiredId = [obj objectForKey:@"objectId"];
            
            [bquery getObjectInBackgroundWithId:[obj objectForKey:@"objectId"] block:^(BmobObject *object, NSError *error) {
                if (error) {
//                    NSLog(@"%s",__func__);
                }else {
                    if (object) {
                        BmobObject *obj2 = [BmobObject objectWithoutDataWithClassName:object.className objectId:object.objectId];
                        [obj2 setObject:thirdCount forKey:@"witchCount"];
                        //异步更新数据
                        [obj2 updateInBackground];
                    }
                }
            }];
        }
    }];
}
- (IBAction)lichengBC:(id)sender {
    LiChengVC *lichengVc = [[LiChengVC alloc] init];
    [self.navigationController pushViewController:lichengVc animated:YES];

}
- (IBAction)wupinBC:(id)sender {
    QZGoodsVC *goods = [[QZGoodsVC alloc] init];
    [self.navigationController pushViewController:goods animated:YES];
}

- (IBAction)gerenBC:(id)sender {
    QZGeRenVC *gerenVc = [[QZGeRenVC alloc] init];
    [self.navigationController pushViewController:gerenVc animated:YES];
}

- (IBAction)signInBC:(id)sender {
    [self setSignBtnStateNormal];
    self.signInB.hidden = NO;
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(signSave:) object:self.signInB];
    [self performSelector:@selector(signSave:) withObject:self.signInB afterDelay:0.2f];
}

- (IBAction)backHomeBC:(id)sender {
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    self.backHomeB.hidden = YES;
    isCloseMargin=NO;
    [self loadFirstData];    
}

- (IBAction)cancleDeskBC:(id)sender {
    [self clearThirdCount];
}
/**更新thirdCount 归零*/
- (void)clearThirdCount
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"thirdCount"];
    [bquery orderByAscending:@"createdAt"];
    [bquery whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    [bquery calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        NSString *thiredId;
        NSString *thirdCount = @"0";
        for (BmobObject *obj in array) {
            thiredId = [obj objectForKey:@"objectId"];
            
            [bquery getObjectInBackgroundWithId:[obj objectForKey:@"objectId"] block:^(BmobObject *object, NSError *error) {
                if (error) {
                }else {
                    if (object) {
                        BmobObject*obj2 = [BmobObject objectWithoutDataWithClassName:object.className objectId:object.objectId];
                        [obj2 setObject:thirdCount forKey:@"thirdC"];
                        
                        NSString *cacheStr = @"0";
                        
                        [obj2 setObject:cacheStr forKey:@"witchCount"];
                        
                        //异步更新数据
                        [obj2 updateInBackground];
                        [self clearPersonDesk];
                        [self.mapView removeAnnotations:self.mapView.annotations];
                        [self.mapView removeOverlays:self.mapView.overlays];
                        self.backHomeB.hidden = YES;
                        isCloseMargin=NO;
                        self.signInB.hidden = YES;
//                        cacheCount = 0;
//                        startI = 100;
                        [self loadFirstData];
                        MKCoordinateSpan span = MKCoordinateSpanMake(0.026416, 0.019511);
                        MKCoordinateRegion region = MKCoordinateRegionMake(self.currentCoordinate, span);
                        [self.mapView setRegion:region animated:YES];
                        self.mapView.showsUserLocation = YES;
                    }
                }
            }];
        }
    }];
}
/**personDesk 归零*/
- (void)clearPersonDesk
{
    BmobQuery *bqueryRemove = [BmobQuery queryWithClassName:@"personDesk"];
    [bqueryRemove orderByAscending:@"createdAt"];
    [bqueryRemove whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    removeOBJArray = [NSMutableArray array];
    [bqueryRemove calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        int f=0;
        for (BmobObject *obj in array) {
            f++;
            NSString *objId = [obj objectForKey:@"objectId"];
            [removeOBJArray addObject:objId];
            if (f == array.count) {
                 BmobObject *bmobDetailObj;
                for (int i = 0; i<startI-100; i++) {
                    bmobDetailObj = [BmobObject objectWithoutDataWithClassName:@"personDesk" objectId:removeOBJArray[i]];
                    [bmobDetailObj deleteInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
                        if (isSuccessful) {
                            isActivate = NO;
                            cacheCount = 0;
                            startI = 100;
                        } else {
                            NSLog(@"%@",error);
                        }
                    }];
                }
            }
        }
    }];
}
- (void)signSave:(UIViewController *)vc
{
    startI++;
    //1. 更新数据
    [self updataThirdCound];
    //2. 保存个人数据
    [self savePersonSignData];

}
- (void)savePersonSignData
{
    BmobObject *personObj = [BmobObject objectWithClassName:@"personDesk"];
    [personObj setObject:[userDefaults1 objectForKey:@"detailSave"] forKey:@"loginUser"];
    CLLocation *loc = thirdCLArray[startI-101];
    [personObj setObject:@(loc.coordinate.latitude) forKey:@"latitude"];
    [personObj setObject:@(loc.coordinate.longitude) forKey:@"longitude"];
    NSString *deskImageStr = thirdGoodsPicA[startI-101];
    [personObj setObject:deskImageStr forKey:@"deskImStr"];
    [personObj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            NSLog(@"ddsfsa");
        }else{
        }
    }];

}

//需要传到里程中的数组  第几条线（表示已经完成的）
- (void)saveThirdOrderData
{
    BmobObject *thirdObject = [BmobObject objectWithClassName:@"thirdOrder"];//在里程中的顺序
    
    NSString *cacheStr = [NSString stringWithFormat:@"%d",cacheCount];
    [thirdObject setObject:[userDefaults1 objectForKey:@"detailSave"] forKey:@"loginUser"];
    NSString *lineNameStrS = lineNameArray[cacheCount-1];
    
    NSString *groupCountStr = [NSString stringWithFormat:@"%d",startI-100];
    
    [thirdObject setObject:groupCountStr forKey:@"groupCountStr"];
    [thirdObject setObject:lineNameStrS forKey:@"lineName"];
    [thirdObject setObject:cacheStr forKey:@"cacheStr"];
    [thirdObject saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
        } else {
//            NSLog(@"%@",error);
        }
    }];
}
//当前任务线的任务数 更新数据
- (void)updataThirdCound
{//签到一个极为1 startI
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"thirdCount"];
    [bquery orderByAscending:@"createdAt"];
    [bquery whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    [bquery calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        NSString *thiredId;
        NSString *thirdCount = [NSString stringWithFormat:@"%d",startI-100];
        for (BmobObject *obj in array) {
            thiredId = [obj objectForKey:@"objectId"];
            
            [bquery getObjectInBackgroundWithId:[obj objectForKey:@"objectId"] block:^(BmobObject *object, NSError *error) {
                if (error) {
                }else {
                    if (object) {
                        BmobObject*obj2 = [BmobObject objectWithoutDataWithClassName:object.className objectId:object.objectId];
                        [obj2 setObject:thirdCount forKey:@"thirdC"];
                        
                        NSString *cacheStr = [NSString stringWithFormat:@"%d",cacheCount];
                        
                        [obj2 setObject:cacheStr forKey:@"witchCount"];
                       
                        //异步更新数据
                        [obj2 updateInBackground];
                        
                        if (startI-100 == [thirdCountArray[cacheCount-1] intValue]) {
                            isActivate = NO;
                            self.backHomeB.hidden = NO;
                            self.signInB.hidden=YES;
                            isCloseMargin=YES;
                        }
                        [self linkline];
                    }
                }
            }];
        }
    }];
}
//签到还应该要把当前的任务保存
- (void)linkline
{
    CLLocationCoordinate2D commonPolylineCoords[2];
//    isLoadFirst = NO;
    if (startI>=102) {
        if (isLoadFirst == YES) {
            CLLocation *loc = thirdCLArray[startI-102];
            touchMapCoordinate = loc.coordinate;
            isLoadFirst = NO;
        } else {}
        commonPolylineCoords[0] = touchMapCoordinate;
    }
    CLLocation *loc = thirdCLArray[startI-101];
    touchMapCoordinate = loc.coordinate;
    
    if (startI >=102) {
        commonPolylineCoords[1] = touchMapCoordinate;
        commonPolyline11 = [MKPolyline polylineWithCoordinates:commonPolylineCoords count:2];
        [self.mapView addOverlay:commonPolyline11];
    }
    NSString *currentCStr = thirdCountArray[cacheCount-1];
    int currentCount = [currentCStr intValue];
    if (startI-100 == currentCount) {
        [self saveThirdOrderData];
    }else {}
}
#pragma mark - 自定义方法
- (void)loadThirdCount
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"breakPoints"];
    [query orderByAscending:@"createdAt"];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        thirdCountArray = [NSMutableArray array];
        int f = 0;
        for (BmobObject *obj in array) {
            f++;
            NSString *breakPoints = [obj objectForKey:@"breakPointCount"];
            [thirdCountArray addObject:breakPoints];
            if (f==array.count) {
                [self loadProgressData];
            }
        }
        
    }];
}
#pragma mark 加载当前任务进度
- (void)loadProgressData//第二步加载
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"thirdCount"];
    [bquery orderByAscending:@"createdAt"];
    [bquery whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    [bquery calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        int f= 0;
        for (BmobObject *obj in array) {
            f++;
            NSString *witchDesk1 = [obj objectForKey:@"witchCount"];
            cacheCount = [witchDesk1 intValue];//哪一条任务
            NSString *witchCount1 = [obj objectForKey:@"thirdC"];
            startI = 100+[witchCount1 intValue];//任务中的哪一个
            if (f == array.count) {
                [self loadFirstData];
            }
        }
        
    }];
}
- (void)loadFirstData//数据加载 第三步加载第一层
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"StartAnnotations"];
    [query orderByAscending:@"createdAt"];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        startDeskmArray = [NSMutableArray array];
        startCLArray = [NSMutableArray array];
        NSString *leftPic;
        NSData *decodedImageData;
        NSString *lineNameStr;
        lineNameArray = [NSMutableArray array];
        startMarkerArray = [NSMutableArray array];
        int countCishu=0;
        for (BmobObject *obj in array) {
            countCishu ++;
            QZAnnotation *deskAn = [[QZAnnotation alloc] init];
            deskAn.coordinate = CLLocationCoordinate2DMake([[obj objectForKey:@"latitude"] doubleValue], [[obj objectForKey:@"longitude"] doubleValue]);
            deskAn.title = [obj objectForKey:@"title"];
            leftPic = [obj objectForKey:@"imageStr"];
            decodedImageData = [[NSData alloc] initWithBase64Encoding:leftPic];
            UIImage *decodedImage      = [UIImage imageWithData:decodedImageData];
            deskAn.image = decodedImage;
            deskAn.marker = [obj objectForKey:@"marker"];
            deskAn.subtitle = [obj objectForKey:@"subtitle"];
            lineNameStr = [obj objectForKey:@"lineName"];
            CLLocation *pCl = [[CLLocation alloc] initWithLatitude:deskAn.coordinate.latitude longitude:deskAn.coordinate.longitude];
            [startCLArray addObject:pCl];
            [startDeskmArray addObject:deskAn];
            [lineNameArray addObject:lineNameStr];
            [startMarkerArray addObject:deskAn.marker];
            if (countCishu == array.count) {
                [self needRemoveData];
            }
        }
        
    }];
}
- (void)needRemoveData//需要移除的
{
    BmobQuery *bqueryRemove = [BmobQuery queryWithClassName:@"thirdOrder"];
    [bqueryRemove orderByAscending:@"createdAt"];
    [bqueryRemove whereKey:@"loginUser" equalTo:[userDefaults1 objectForKey:@"detailSave"]];
    
    [bqueryRemove calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        removeArray = [NSMutableArray array];
        for (BmobObject *objRemove in array) {
            NSString *removeStr = [objRemove objectForKey:@"cacheStr"];
            [removeArray addObject:removeStr];
        }
            //移除
            NSMutableIndexSet *indexSets = [[NSMutableIndexSet alloc] init];
            for (int i = 0; i<removeArray.count; i++) {
                [indexSets addIndex:[removeArray[i] intValue]-1];
            }
            [startDeskmArray removeObjectsAtIndexes:indexSets];
            [startCLArray removeObjectsAtIndexes:indexSets];
            [startMarkerArray removeObjectsAtIndexes:indexSets];
        int howMany = 0 ;
        if (cacheCount ==0) {
        } else {
             howMany = [thirdCountArray[cacheCount-1] intValue];
        }
        if (cacheCount>0&&startI-100<howMany) {

            [self loadThirdData];
            isActivate = YES;
        } else {
            [self.mapView addAnnotations:startDeskmArray];//加载处理后的第一层数据
        }
    }];
}
- (void)loadSecondData
{
    BmobQuery *query = [BmobQuery queryWithClassName:@"annotations"];
    [query orderByAscending:@"createdAt"];
    [query calcInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        secondDeskArray = [NSMutableArray array];
        secondGoodsPicA = [NSMutableArray array];
        secondPicArray = [NSMutableArray array];
        secondCLArray = [NSMutableArray array];
        NSString *leftPic;
        NSString *deskImaStr;
        NSData *decodedImageData;
        for (BmobObject *obj in array) {
            QZAnnotation *deskAn = [[QZAnnotation alloc] init];
            deskAn.coordinate = CLLocationCoordinate2DMake([[obj objectForKey:@"latitude"] doubleValue], [[obj objectForKey:@"longitude"] doubleValue]);
            deskAn.title = [obj objectForKey:@"title"];
            leftPic = [obj objectForKey:@"imageStr"];
            deskImaStr = [obj objectForKey:@"deskImStr"];
            
            decodedImageData = [[NSData alloc] initWithBase64Encoding:leftPic];
            UIImage *decodedImage      = [UIImage imageWithData:decodedImageData];
            deskAn.image = decodedImage;
            
            deskAn.subtitle = [obj objectForKey:@"subtitle"];
          CLLocation *pCl = [[CLLocation alloc] initWithLatitude:deskAn.coordinate.latitude longitude:deskAn.coordinate.longitude];
            [secondCLArray addObject:pCl];
            [secondPicArray addObject:leftPic];
            [secondDeskArray addObject:deskAn];
            [secondGoodsPicA addObject:deskImaStr];
        }
    }];
}
#pragma mark 加载第三层任务
- (void)loadThirdData
{
    int start = 0;
    int end = 0;
    thirdDeskArray = [NSMutableArray array];
    thirdCLArray = [NSMutableArray array];
    thirdPicArray = [NSMutableArray array];
    thirdGoodsPicA = [NSMutableArray array];
    for (int i = 0; i<thirdCountArray.count; i++) {
        if (cacheCount ==1) {
            start = 0;
        } else{
            if (i< cacheCount-1) {
                start = [thirdCountArray[i] intValue]+start;
            }
        }
    }
    end = start + [thirdCountArray[cacheCount-1] intValue];
    for (int i =0; i<secondDeskArray.count; i++) {
        if (i>=start &&i<end) {
            [thirdPicArray addObject:secondPicArray[i]];
            [thirdDeskArray addObject:secondDeskArray[i]];
            [thirdCLArray addObject:secondCLArray[i]];
            [thirdGoodsPicA addObject:secondGoodsPicA[i]];
        }
    }
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView addAnnotations:thirdDeskArray];
    [self linkLines];
}
- (void)linkLines
{
    int pointCount = (int)thirdCLArray.count;
    CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i<pointCount; ++i) {
        CLLocation *location = [thirdCLArray objectAtIndex:i];
        coordinateArray[i] = [location coordinate];
    }
    grayLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mapView addOverlay:grayLine];
        [self.mapView setVisibleMapRect:[grayLine boundingMapRect] animated:YES];
    });
    
}


@end
